<script setup lang="ts">
import { isNullOrEmpty } from '@/utils/functions'
import { useI18n } from "vue-i18n";
import { ref, reactive } from "vue";
import Motion from "../utils/motion";
import { message } from "@/utils/message";
import { phoneRules } from "../utils/rule";
import { ElMessage, type FormInstance } from "element-plus";
import { useVerifyCode } from "../utils/verifyCode";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
// import Iphone from "@iconify-icons/ep/iphone";
import { getPhoneCode, loginPhone } from "@/api/user";
import { useUserStoreHook } from "@/store/modules/user";
import { addPathMatch } from "@/router/utils";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { getSelfInfo } from "@/api/user";
import { removeToken, setUserKey } from '@/utils/auth'
import { resetHomePage, resetRouter } from '@/router/index'
import { debounce, deviceDetection, storageLocal } from "@pureadmin/utils";
import { PLATFORM_Map, initManageUnit, initOperateUnit, initScreenUnit, usePageVariablesStoreHook } from '@/store/modules/pageVariables'
import { openProtocolContent, robotVerification } from '../utils/functions'
import { useGlobal } from "@pureadmin/utils";
import { useDataDashboardThemeStoreHook } from '@/store/modules/data-dashboard-theme';

import user from '@/assets/images/svg/user.svg'
import password from '@/assets/images/svg/password.svg'
import phone from '@/assets/images/svg/phone.svg'
import code from '@/assets/images/svg/code.svg'
import { addDialog } from '@/components/ReDialog';
const config = ref(useGlobal().$config)
const emits = defineEmits(["goRegist"]);
const loading = ref(false);
const ruleForm = reactive({
  phone: "",
  telCode: ""
});
const ruleFormRef = ref<FormInstance>();
const { isDisabled, text, start, end } = useVerifyCode('phone');
const router = useRouter();
const checked = ref(false);

const onLogin = async (formEl: FormInstance | undefined) => {
  storageLocal().removeItem('manage')
  storageLocal().removeItem('operate')
  if (!checked.value) {
    message(`请先勾选同意《${isNullOrEmpty(config.value.ProtocolName)}》`, { type: "warning" });
    return;
  };
  if (!formEl) return;
  loading.value = true;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByPhone(ruleForm)
        .then(res => {
          // 全部采取静态路由模式
          getSelfInfo().then(res => {
            let data = res.result;
            setUserKey(data.userInfo.nickname, data.permissions, data.userInfo);
            usePageVariablesStoreHook().clear();
            if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.operate) {
              initOperateUnit().then(() => {
                resetHomePage()
                resetRouter();
                message("登录成功", { type: "success" });
              });
            } else if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.manage) {
              initManageUnit().then(() => {
                resetHomePage()
                resetRouter();
                message("登录成功", { type: "success" });
              });
            } else if (usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.data || usePageVariablesStoreHook().getPlatform() == PLATFORM_Map.monitor) {
              initScreenUnit().then(() => {
                useDataDashboardThemeStoreHook().reDataDashboardThemeStore()
                resetHomePage()
                resetRouter();
                message("登录成功", { type: "success" });
              });
            } else {
              message("暂无可登录平台，请联系管理员！", { type: "error" });
              removeToken();
            }
            // usePermissionStoreHook().handleWholeMenus([]);
            // addPathMatch();
            // router.push("/");
          });
        })
        .finally(() => {
          setTimeout(() => {
            loading.value = false
          }, 1000)
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

function onBack() {
  end();
  useUserStoreHook().SET_CURRENTPAGE(0);
}
function getPhoneCodes() {
  ruleFormRef.value.validateField('phone', isValid => {
    if (isValid) {
      getRobotVerification()
    }
  })
}

const getRobotVerification = debounce(() => {
  robotVerification({
    fun: getPhoneCode,
    param: { phone: ruleForm.phone },
    successFun: () => {
      start(ruleFormRef.value, 'phone')
    }
  })
}, 500, true)
</script>

<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="phoneRules" size="large">
    <Motion>
      <el-form-item prop="phone">
        <el-input v-model="ruleForm.phone" clearable placeholder="请输入手机号" :prefix-icon="useRenderIcon(phone)"
          v-bind="$attrs" />
      </el-form-item>
    </Motion>

    <Motion :delay="100">
      <el-form-item prop="telCode">
        <div class="w-full flex justify-between">
          <el-input v-model="ruleForm.telCode" clearable placeholder="短信验证码" v-bind="$attrs"
            :prefix-icon="useRenderIcon(code)" />
          <!-- <el-button :disabled="isDisabled" class="ml-2 !border-[#fff]" @click="getPhoneCodes"> -->
          <el-button :disabled="isDisabled" class="ml-2" @click="getPhoneCodes">
            <div class="text-[var(--el-color-primary)]">
              <!-- <div class="text-[#fff]"> -->
              {{ isNullOrEmpty(text.length > 0 ? text + ' s后重新获取' : '获取验证码') }}
            </div>
          </el-button>
        </div>
      </el-form-item>
    </Motion>

    <Motion :delay="150">
      <!-- <el-form-item> -->
      <el-button class="w-full" size="default" type="primary" :loading="loading" @click="onLogin(ruleFormRef)">
        登录
      </el-button>
      <!-- </el-form-item> -->
    </Motion>
    <Motion :delay="200">
      <!-- <el-form-item> -->
      <div class=" w-full flex-bc">
        <div class="flex-c">
          <el-checkbox v-model="checked">
            <div class="text-[#fff]">我已阅读并同意</div>
          </el-checkbox>
          <el-button link type="primary" style="--el-color-primary: #fe861c;--el-color-primary-light-5: #fe861c;"
            @click="openProtocolContent(config.ProtocolName, config.ProtocolContent)">
            《{{ isNullOrEmpty(config.ProtocolName) }}》
          </el-button>
        </div>
        <div class="flex-c" style="--el-color-primary: #fff;--el-color-primary-light-5: #fff;">
          <el-button link type="primary" @click="emits('goRegist')">
            立即注册
          </el-button>
        </div>
      </div>
      <!-- </el-form-item> -->
    </Motion>
    <!-- <Motion :delay="200">
      <el-form-item>
        <el-button class="w-full" size="default" @click="onBack">
          返回
        </el-button>
      </el-form-item>
    </Motion> -->
  </el-form>
</template>
